import Vue from 'vue';
import Vuex from 'vuex';

import * as actionTypes from './constants/action-types';
import * as mutationTypes from './constants/mutation-types';
import auth from './utils/auth';
import utils from './utils/utils';
import * as api from './constants/api';
import ajax from './utils/ajax';

Vue.use(Vuex);

const state = {
  userinfo: null,
  menus:[
    {
      path: "/home",
      text: "首页",
      icon: 'el-icon-tickets',
    },{
      path: "/table",
      text:"table示例",
      icon: 'el-icon-tickets',
    },{
      path: '/form',
      text: '2级菜单',
      icon: 'el-icon-tickets',
      children:[
        {
          path: '/form/index',
          text: 'form示例',
          icon: 'el-icon-tickets',
        },{
          path: '/form/other',
          text: '第二个菜单',
          icon: 'el-icon-tickets',
          activePath: "/form/other",
        }
      ]
    }
  ],
  breadcrumbs:[
    {path: '/home', text: '首页'},
    {path: '/form/index', text: '当前页'}
  ]
}

const getters = {
  
}

const mutations ={
  [mutationTypes.SET_USERINFO](state, payload){
    state.userinfo = payload.userinfo;
  },
  [mutationTypes.SET_MENUS](state, payload){
    state.menus = payload.menus;
  },
  [mutationTypes.SET_BREADCRUMBS](state, payload){
    state.breadcrumbs = payload.breadcrumbs;
  }
}

const actions = {
  [actionTypes.LOGIN]({commit}, loginForm){
    return new Promise((resolve, reject)=>{
      ajax.post(api.LOGIN, loginForm).then(data=>{
        auth.login(data)
        resolve(data)
      }).catch(err=>{
        reject(err)
      })
    })
  },
  [actionTypes.LOGOUT]({commit}){
    return new Promise((resolve, reject)=>{
      ajax.post(api.LOGOUT).then(data=>{
        auth.logout()
        resolve(data)
      }).catch(err=>{
        reject(err)
      })
    })
  },
  [actionTypes.USERINFO]({commit}){
    return new Promise((resolve, reject)=>{
      ajax.post(api.USERINFO).then(data=>{
        commit({
          type:mutationTypes.SET_USERINFO,
          userinfo: data,
        });
        resolve(data);
      }).catch(err=>{
        reject(err);
      })
    })
  }
}

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
});
